package com.lzj.jiangxindaojia.view.login;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ifaa.sdk.api.AuthenticatorManager;
import com.ifaa.sdk.auth.AuthenticatorCallback;
import com.ifaa.sdk.auth.Constants;
import com.ifaa.sdk.auth.IAuthenticator;
import com.ifaa.sdk.auth.message.AuthenticatorMessage;
import com.ifaa.sdk.auth.message.AuthenticatorResponse;
import com.lzj.jiangxindaojia.R;
import com.lzj.jiangxindaojia.base.BaseActivity;
import com.lzj.jiangxindaojia.bean.FingerLogin;
import com.lzj.jiangxindaojia.bean.FingerRegistInit;
import com.lzj.jiangxindaojia.bean.ResultCode;
import com.lzj.jiangxindaojia.http.HttpAction;
import com.lzj.jiangxindaojia.http.HttpCallBack;
import com.lzj.jiangxindaojia.http.HttpConstans;
import com.lzj.jiangxindaojia.http.HttpUtil;
import com.lzj.jiangxindaojia.utils.GsonUtil;
import com.lzj.jiangxindaojia.utils.LogUtils;
import com.lzj.jiangxindaojia.utils.MD5;
import com.lzj.jiangxindaojia.utils.SharePreferenceUtil;
import com.lzj.jiangxindaojia.utils.Utils;
import com.lzj.jiangxindaojia.view.login.ali.FingerPrintAuthActivity;
import com.lzj.jiangxindaojia.view.login.ali.FingerPrintToast;
import com.lzj.jiangxindaojia.view.login.ali.IFAAFingerprintOpenAPI;

import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by lizj on 2017/12/5.
 */

public class SettingZwLoginActivity extends BaseActivity implements HttpCallBack {
    private TextView tv_tile, btn_pwdlogin;
    private ImageView iv_left;
    private LinearLayout ll_left;
    private Button btn_zhiwenlogin;
    private HttpCallBack httpcallback;

    private String token = "";
    private String open_info = "";
    private String user_id = "";
    private String secData = "";
    private Process curProcess = Process.REG_GETREQ;

    public enum Process {
        REG_GETREQ, REG_SENDRESP, AUTH_GETREQ, AUTH_SENDRESP, MUITLFINGERS_AUTH_SENDRESP, DEREG_GETREQ
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_REGDISABLE:
//                                regBtn.setEnabled(false);
                    break;
                case MSG_REGENABLE:
//                                regBtn.setEnabled(true);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void initData() {
        super.initData();
        this.tv_tile = ((TextView) findViewById(R.id.tv_tile));
        this.iv_left = ((ImageView) findViewById(R.id.iv_left));
        this.ll_left = ((LinearLayout) findViewById(R.id.ll_left));
        this.tv_tile.setText(R.string.login_openzhiwenlogin);
        iv_left.setImageResource(R.mipmap.back);
        this.ll_left.setVisibility(View.VISIBLE);
        this.btn_zhiwenlogin = ((Button) findViewById(R.id.btn_zhiwenlogin));
        this.btn_pwdlogin = ((TextView) findViewById(R.id.btn_pwdlogin));

        token = SharePreferenceUtil.getData(this, SharePreferenceUtil.USERINFO, SharePreferenceUtil.TOKEN);
        open_info = SharePreferenceUtil.getData(this, SharePreferenceUtil.USERINFO, SharePreferenceUtil.OPEN_INFO);
        user_id = SharePreferenceUtil.getData(this, SharePreferenceUtil.USERINFO, SharePreferenceUtil.USER_ID);

        httpcallback = this;


    }

    @Override
    protected void requestServer() {
        super.requestServer();

    }

    @Override
    protected void setListener() {
        super.setListener();
        btn_zhiwenlogin.setOnClickListener(this);
        btn_pwdlogin.setOnClickListener(this);
        ll_left.setOnClickListener(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_settingzhiwenlogin;
    }

    private int authType = Constants.TYPE_FINGERPRINT;
    public static IAuthenticator authenticator;
    private final int MSG_REGENABLE = 1;
    private final int MSG_REGDISABLE = 2;
    private HashMap paramMap;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_zhiwenlogin:
                /**
                 * 检测是否支持IFAA
                 */
                if (!AuthenticatorManager.isSupportIFAA(this, authType)) {
                    Toast.makeText(this, "This device not support IFAA", Toast.LENGTH_LONG).show();
                    return;
                }
                authenticator = AuthenticatorManager.create(this, authType, "JXDJ");
                LogUtils.log("hasEnrolled:" + authenticator.hasEnrolled());
                if (!authenticator.hasEnrolled()) {//是否录过指纹
                    authenticator.startSystemEnrollManger();//去系统设置页面录指纹
                }

                curProcess = Process.REG_GETREQ;
                /**
                 * 获得授权数据
                 */
                String info = AuthenticatorManager.getAuthData(this, SharePreferenceUtil.getData(this, SharePreferenceUtil.USERINFO, SharePreferenceUtil.USER_ID));
//                    IFAAFingerprintOpenAPI.getInstance().getRegRequestAsyn(info, callback);
                secData = info;
                SharePreferenceUtil.keepDate(this, SharePreferenceUtil.TOKENFILE, SharePreferenceUtil.SEC_DATA, secData);
                LogUtils.log("reg info:" + info);

                paramMap = new HashMap();
                paramMap.put("type", "1");
                paramMap.put("auth_type", "1");
                paramMap.put("app_id", HttpConstans.appid);
                paramMap.put("channel_number", HttpConstans.qdnumber);
                paramMap.put("open_info", open_info);
                paramMap.put("token", token);
                paramMap.put("sec_data", secData);
                LogUtils.log("sin " + MD5.createSignString(paramMap));
                paramMap.put("sign", MD5.md5(MD5.createSignString(paramMap) + HttpConstans.KEY));
                HttpUtil.getInstance(this).postAsynHttp(HttpConstans.BASEURL + HttpConstans.FINGER_REGIST_INIT, paramMap, this, this, HttpAction.FINGER_REGIST_INIT);


                break;
            case R.id.btn_pwdlogin:
                showDialogs();
                break;
            case R.id.ll_left:
                finish();
                break;
        }
    }


    private FingerRegistInit fingerRegistInit;
    private FingerLogin fingerLogin;

    @Override
    public <T> void onSuccess(String result, String action) {
        switch (action) {
            case HttpAction.FINGER_REGIST_INIT:
                fingerRegistInit = GsonUtil.GsonToBean(result, FingerRegistInit.class);
                if (ResultCode.SUCCESS.equals(fingerRegistInit.getStatus())) {
                    startFPActivity(false);
                    AuthenticatorMessage requestMessage = new AuthenticatorMessage(AuthenticatorMessage.MSG_REGISTER_REQUEST, 2);
                    requestMessage.setData(fingerRegistInit.getData().getContent());
                    authenticator.process(requestMessage, regCallback);
                } else {
                    Utils.showToast(SettingZwLoginActivity.this, fingerRegistInit.getMsg());

                }
                break;
            case HttpAction.FINGER_LOGIN_REGIST:
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String status = jsonObject.getString("status");
                    String msg = jsonObject.getString("msg");
                    String data = jsonObject.getString("data");
                    if (ResultCode.SUCCESS.equals(status)) {
                        token = data;
                        SharePreferenceUtil.keepDate(this, SharePreferenceUtil.TOKENFILE, SharePreferenceUtil.REGIST_LOGINTOKEN, token);
                        finish();
                    } else {
                        Utils.showToast(this, msg);
                    }
                    /**
                     * 指纹页面消失
                     */
                    FingerprintBroadcastUtil.sendIdentifyStatusChangeMessage(SettingZwLoginActivity.this, 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }


    private AuthenticatorCallback regCallback = new AuthenticatorCallback() {
        @Override
        public void onStatus(int status) {
            FingerprintBroadcastUtil.sendIdentifyStatusChangeMessage(SettingZwLoginActivity.this, status);
        }

        @Override
        public void onResult(final AuthenticatorResponse response) {
            final String data = response.getData();
            LogUtils.log("reg respone info:" + data);
            curProcess = Process.REG_SENDRESP;
            if (response.getResult() == AuthenticatorResponse.RESULT_SUCCESS) {
//                IFAAFingerprintOpenAPI.getInstance().sendRegResponeAsyn(data, secData, callback);
                paramMap = new HashMap();
                paramMap.put("type", "2");
                paramMap.put("token_type", "login_token");
                paramMap.put("app_id", HttpConstans.appid);
                paramMap.put("channel_number", HttpConstans.qdnumber);
                paramMap.put("open_info", open_info);
                paramMap.put("token", token);
                paramMap.put("user_id", user_id);
                paramMap.put("ifaf_message", data);
                paramMap.put("sec_data", secData);
                paramMap.put("sign", MD5.md5(MD5.createSignString(paramMap) + HttpConstans.KEY));
                HttpUtil.getInstance(SettingZwLoginActivity.this).postAsynHttp(HttpConstans.BASEURL + HttpConstans.FINGER_LOGIN_REGIST, paramMap, SettingZwLoginActivity.this, httpcallback, HttpAction.FINGER_LOGIN_REGIST);
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        new FingerPrintToast(SettingZwLoginActivity.this, FingerPrintToast.ST_REGFAIL).show("reg fail:" + response.getResult());
                        FingerprintBroadcastUtil.sendIdentifyStatusChangeMessage(SettingZwLoginActivity.this, 0);
                    }
                });
            }
        }
    };


    private AuthenticatorResponse authenticatorResponse;
    private AuthenticatorCallback authCallback = new AuthenticatorCallback() {
        @Override
        public void onStatus(int status) {
            FingerprintBroadcastUtil.sendIdentifyStatusChangeMessage(SettingZwLoginActivity.this, status);
        }

        @Override
        public void onResult(final AuthenticatorResponse response) {
            authenticatorResponse = response;
            String data = response.getData();
            curProcess = Process.AUTH_SENDRESP;
            if (response.getResult() == AuthenticatorResponse.RESULT_SUCCESS) {
                IFAAFingerprintOpenAPI.getInstance().sendAuthResponeAsyn(data, secData, callback);
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        new FingerPrintToast(SettingZwLoginActivity.this, FingerPrintToast.ST_AUTHTEEFAIL).show("auth tee fail:" + response.getResult());
                        FingerprintBroadcastUtil.sendIdentifyStatusChangeMessage(SettingZwLoginActivity.this, 0);
                    }
                });

            }
        }
    };

    private AuthenticatorCallback deregCallback = new AuthenticatorCallback() {
        @Override
        public void onStatus(int status) {
            FingerprintBroadcastUtil.sendIdentifyStatusChangeMessage(SettingZwLoginActivity.this, status);

        }

        @Override
        public void onResult(final AuthenticatorResponse response) {
            String data = response.getData();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (response.getResult() == AuthenticatorResponse.RESULT_SUCCESS) {
                        new FingerPrintToast(SettingZwLoginActivity.this, FingerPrintToast.ST_DEREGSUCCESS).show(null);
                        saveToken("");
                        handler.sendEmptyMessage(MSG_REGENABLE);
                    } else {
                        new FingerPrintToast(SettingZwLoginActivity.this, FingerPrintToast.ST_DEREGFAIL).show("dereg fail:" + response.getResult());
                    }
                }
            });
        }
    };

    private IFAAFingerprintOpenAPI.Callback callback = new IFAAFingerprintOpenAPI.Callback() {
        @Override
        public void onCompeleted(final int status, final String info) {
            LogUtils.log("opanapi resp:" + info);
            switch (curProcess) {
                case REG_GETREQ:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            startFPActivity(false);
                            AuthenticatorMessage requestMessage = new AuthenticatorMessage(AuthenticatorMessage.MSG_REGISTER_REQUEST, 2);
                            requestMessage.setData(info);
                            authenticator.process(requestMessage, regCallback);

                        }
                    });
                    break;
                case REG_SENDRESP:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (status == 0) {
                                new FingerPrintToast(SettingZwLoginActivity.this, FingerPrintToast.ST_REGSUCCESS).show("");
                                saveToken(IFAAFingerprintOpenAPI.getInstance().getToken());
                                token = IFAAFingerprintOpenAPI.getInstance().getToken();
                                handler.sendEmptyMessage(MSG_REGDISABLE);

                            } else {
                                new FingerPrintToast(SettingZwLoginActivity.this, FingerPrintToast.ST_REGFAIL).show("ifaa reg fail");
                            }
                            FingerprintBroadcastUtil.sendIdentifyStatusChangeMessage(SettingZwLoginActivity.this, 0);
                        }
                    });
                    break;
                case AUTH_GETREQ:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            startFPActivity(false);
                            AuthenticatorMessage requestMessage = new AuthenticatorMessage(AuthenticatorMessage.MSG_AUTHENTICATOR_REQUEST, 2);
                            requestMessage.setData(info);
                            authenticator.process(requestMessage, authCallback);

                        }
                    });
                    break;
                case AUTH_SENDRESP:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (status == 0) {
                                new FingerPrintToast(SettingZwLoginActivity.this, FingerPrintToast.ST_AUTHSUCCESS).show("");
                            } else {
//                                if (info.equals("IFAA_ERR_WRONG_AUTHDATAINDEX") && multifingersCb.isChecked() && IFAAFingerprintOpenAPI.checkFingerId) {
//                                    if (authenticatorResponse != null) {
//                                        curProcess = Process.MUITLFINGERS_AUTH_SENDRESP;
//                                        IFAAFingerprintOpenAPI.getInstance().sendAuthUpdateMultiFingersResponeAsyn(authenticatorResponse.getData(), secData, callback);
//                                    }
//
//                                } else {
//                                    new FingerPrintToast(SettingZwLoginActivity.this, FingerPrintToast.ST_AUTHFAIL).show("ifaa auth fail");
//                                }
                            }
                            FingerprintBroadcastUtil.sendIdentifyStatusChangeMessage(SettingZwLoginActivity.this, 0);
                        }
                    });
                    break;
                case MUITLFINGERS_AUTH_SENDRESP:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (status == 0) {
                                new FingerPrintToast(SettingZwLoginActivity.this, FingerPrintToast.ST_AUTHSUCCESS).show("更新指位成功");
                            } else {
                                new FingerPrintToast(SettingZwLoginActivity.this, FingerPrintToast.ST_AUTHFAIL).show("更新指纹失败");
                            }
                        }
                    });
                    break;
                case DEREG_GETREQ:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            AuthenticatorMessage requestMessage = new AuthenticatorMessage(AuthenticatorMessage.MSG_DEREGISTER_REQUEST, 2);
                            requestMessage.setData(info);
                            authenticator.process(requestMessage, deregCallback);

                        }
                    });
                    break;
                default:
                    break;
            }
        }
    };


    private AlertDialog dialog;
    private TextView tip_msg;
    private TextView tip_title;
    private TextView ok;
    private TextView cancel;

    private void showDialogs() {
        this.dialog = new AlertDialog.Builder(this, R.style.AppBaseTheme1).create();
        this.dialog.show();
        Window localWindow = this.dialog.getWindow();
        localWindow.clearFlags(131072);
        localWindow.setContentView(R.layout.dialog_tips_two);
        localWindow.setGravity(17);
        localWindow.setLayout(-1, -2);
        LinearLayout localLinearLayout = (LinearLayout) localWindow.findViewById(R.id.ll_dialog);
        int j;
        int i;
        j = Color.parseColor("#FFFFFF");
        i = Color.parseColor("#FFFFFF");
        GradientDrawable localGradientDrawable = new GradientDrawable();
        localGradientDrawable.setColor(i);
        localGradientDrawable.setCornerRadius(10);
        localGradientDrawable.setStroke(5, j);
        localLinearLayout.setBackgroundDrawable(localGradientDrawable);
        this.ok = ((TextView) localWindow.findViewById(R.id.tip_ok));
        this.cancel = ((TextView) localWindow.findViewById(R.id.tip_cancle));
        this.tip_title = ((TextView) localWindow.findViewById(R.id.tip_title));
        this.tip_msg = ((TextView) localWindow.findViewById(R.id.tip_msg));

        this.ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View paramAnonymousView) {
                dialog.dismiss();
            }
        });
        this.cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View paramAnonymousView) {
                dialog.dismiss();
            }
        });
    }


    /**
     * @author qiyi.wxc
     * @version $Id: FingerprintBroadcastUtil.java, v 0.1 2015年12月14日 下午7:44:55 qiyi.wxc Exp $
     */
    public static class FingerprintBroadcastUtil {

        //The is the broadcast for update UI status
        public final static String BROADCAST_FINGERPRINTSENSOR_STATUS_ACTION = "com.ifaa.sdk.authenticatorservice.broadcast.FINGERPRINTSENSOR_STATUS_ACTION";
        public final static String FINGERPRINTSENSOR_STATUS_VALUE = "com.ifaa.sdk.authenticatorservice.broadcast.FINGERPRINTSENSOR_STATUS_VALUE";

        //Send the UI Status of the FingerPrint Result and Change the UI
        public static void sendIdentifyStatusChangeMessage(Context context, int resultCode) {
            Intent broadcastIntent = new Intent(BROADCAST_FINGERPRINTSENSOR_STATUS_ACTION);
            broadcastIntent.putExtra(FINGERPRINTSENSOR_STATUS_VALUE, resultCode);
            broadcastIntent.setPackage(context.getPackageName());
            context.sendBroadcast(broadcastIntent);
        }

        public static IntentFilter getIdentifyChangeBroadcastFilter() {
            IntentFilter filter = new IntentFilter();
            filter.addAction(BROADCAST_FINGERPRINTSENSOR_STATUS_ACTION);
            return filter;
        }

    }

    public void startFPActivity(boolean isAuthenticate) {
        Intent intent = new Intent();
//        if (isAuthenticate) {
//            intent.putExtra(AuthenticatorMessage.KEY_OPERATIONT_TYPE,
//                    AuthenticatorMessage.MSG_AUTHENTICATOR_REQUEST);
//        }
        intent.setClass(this, FingerPrintAuthActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.startActivity(intent);

    }


    private final String TOKENFILE = "user";
    private final String KEY_TOKEN = "token";

    private void saveToken(String token) {
        SharedPreferences sharedPreferences = getSharedPreferences(TOKENFILE, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_TOKEN, token);
        editor.commit();

    }

    private String getToken() {
        SharedPreferences sharedPreferences = getSharedPreferences(TOKENFILE, MODE_PRIVATE);
        return sharedPreferences.getString(KEY_TOKEN, "");
    }
}
